Jerry
                      
                      
                          
                          2019年6月22日
                      
                      
                          
                          1985
                       
                  
              最近搞个命令行小程序,需要实现个延时打点,结果研究了半天才搞定。。咋回事呢?!
测试代码很简单,如下:
from time import sleep
from threading import Thread
isDone = False
def itask():
    global isDone
    sleep(7)
    isDone = True
if __name__ == '__main__':
    print("Task is running, please wait", end="")
    Thread(target = itask).start()
    while(True):
        if isDone == False:
            print(".", end="")
            sleep(0.5)
        else:
            print("Done!")
            break
其实就是主线程内新创建了个子线程来处理其他业务,同时打点计时,子进程完成后通过标记位来通知主线程完成。
理想中的效果图如下:

这段程序在Python IDLE里面运行起来没啥问题,但是在windows的命令行里运行起来就不行了。。

可以看到,程序并没有进行打点,而是子线程完成后也就是sleep结束后全部输出。
研究了半天最后发现了print里面有一个flush参数:
flush值为True或者False,默认为Flase,表示是否立刻将输出语句输入到参数file指向的对象中(默认是sys.stdout)。
上述代码中给print添加“flush=True”后就可以完成我要的功能了。
print(".", end="")
修改为
print(".", end="", flush=True)

                  
                  原创文章,转载请注明出处:
                  https://jerrycoding.com/article/print_flush
              
              
 
              
          微信
          
        
        
        
          支付宝
          
        
      
        